<template>
  <div class="supplier-container">
    <!-- 顶部操作栏 -->
    <div class="action-bar">
      <div class="action-buttons">
        <el-button type="primary" size="default" @click="openAddDialog(null)">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
        <el-button type="danger" size="default" :disabled="!selectedRows.length" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon>
          删除
        </el-button>
        <el-button @click="EXcel">
          导出
        </el-button>
      </div>
      
      <div class="search-tools">
        <el-button type="text" size="small" @click="refreshData" title="刷新">
          <el-icon><RefreshLeft /></el-icon>
        </el-button>
        <el-button type="text" size="small" @click="showAdvancedSearch = !showAdvancedSearch" title="搜索">
          <el-icon><Search /></el-icon>
        </el-button>
        <el-button type="text" size="small" title="视图切换">
          <el-icon><Grid /></el-icon>
        </el-button>
        <el-button type="text" size="small" title="设置">
          <el-icon><Setting /></el-icon>
        </el-button>
      </div>
    </div>
    <transition name="fade">
      <div class="selected-info" v-if="selectedRows.length > 0">
        <span class="selected-text">已选{{ selectedRows.length }}项</span>
        <el-button type="text" size="small" @click="cancelSelection">
          取消选择
        </el-button>
      </div>
    </transition>

    <!-- 表格 -->
    <el-table 
      ref="tableRef"
      :data="tableData" 
      style="width: 100%" 
      border
      @selection-change="handleSelectionChange"
      highlight-current-row
    >
     <el-table-column type="selection" width="55" />
      <el-table-column prop="supplierCode" label="供应商编码" width="120" />
      <el-table-column prop="supplierName" label="供应商名称" width="150" />
      <el-table-column prop="supplierAbbreviation" label="社会信用代码" width="200" />
      <el-table-column prop="supplierAddress" label="供应商地址" width="200" />
      <el-table-column prop="supplierComments" label="备注" width="150" />
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #header>
          <div class="column-header-with-search">
            <span>创建时间</span>
            <el-icon @click="showColumnSearch.createTime = !showColumnSearch.createTime" class="search-icon">
              <Search />
            </el-icon>
          </div>
        </template>
        <template #default="scope">
          {{ scope.row.createTime ? moment(scope.row.createTime).format("YYYY年MM月DD日") : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="修改时间" width="180">
        <template #header>
          <div class="column-header-with-search">
            <span>修改时间</span>
            <el-icon @click="showColumnSearch.updateTime = !showColumnSearch.updateTime" class="search-icon">
              <Search />
            </el-icon>
          </div>

        </template>
        <template #default="scope">
          {{ scope.row.updateTime ? moment(scope.row.updateTime).format("YYYY年MM月DD日") : '' }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="openAddDialog(scope.row)" class="operation-btn">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button link type="danger" size="small" @click="handleDelete(scope.row)" class="operation-btn">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <span class="total-text">共{{Page.totalCount}}条数据</span>
      <el-pagination
        v-model:current-page="Page.Pageindex"
        v-model:page-size="Page.PageSize"
        :page-sizes="[5,10,15,20]"
        layout="prev, pager, next, jumper, sizes"
        :total="Page.totalCount"
        prev-text="上一页"
        next-text="下一页"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="addDialogVisible.is"
      :title="addDialogVisible.title"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      center
    >
      <el-form :model="formData" label-width="120px">
        <el-form-item label="供应商编号">
          <el-input
            v-model="formData.supplierCode"
            clearable
            placeholder="请输入供应商编号"
          />
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input
            v-model="formData.supplierName"
            clearable
            placeholder="请输入供应商名称"
          />
        </el-form-item>
        <el-form-item label="供应商简称">
          <el-input
            v-model="formData.supplierAbbreviation"
            clearable
            placeholder="请输入供应商简称"
          />
        </el-form-item>
        <el-form-item label="联系信息">
          <el-input
            v-model="formData.contactInformation"
            clearable
            placeholder="请输入联系信息"
          />
        </el-form-item>
        <el-form-item label="社会信用代码">
          <el-input
            v-model="formData.socialCreditCode"
            clearable
            placeholder="请输入社会信用代码"
          />
        </el-form-item>
        <el-form-item label="供应商地址">
          <el-input
            v-model="formData.supplierAddress"
            clearable
            placeholder="请输入供应商地址"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formData.supplierComments"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible.is = false">取消</el-button>
          <el-button type="primary" @click="handleAddConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElTable, ElMessageBox, ElForm, ElMessage } from 'element-plus';
import {
  RefreshLeft, Search, Grid, ArrowRight, ArrowLeft,
  Plus, Download, Delete, Edit, Setting
} from '@element-plus/icons-vue';
import { APIs } from '@/Http/http';
import moment from 'moment';
import { useCounterStore } from '@/stores/counter';

// 表格引用
const tableRef = ref<InstanceType<typeof ElTable>>();

// 表格数据
const tableData = ref([]);

// 显示高级搜索
const showAdvancedSearch = ref(false);

// 显示列搜索
const showColumnSearch = reactive({
  supplierCode: false,
  supplierName: false,
  supplierAbbreviation: false,
  contactInformation: false,
  socialCreditCode: false,
  supplierAddress: false,
  createTime: false,
  updateTime: false
});

// 选中的行
const selectedRows = ref<any[]>([]);

// 新增弹窗
const addDialogVisible = reactive({
  title: "",
  is: false
});

// 表单数据
const formData = reactive({
  "supplierId": "",
  "supplierCode": "",
  "supplierName": "",
  "supplierAbbreviation": "",
  "contactInformation": "",
  "socialCreditCode": "",
  "supplierAddress": "",
  "supplierComments": "",
  "createName": ""
});

// 分页信息
const Page = reactive({
  Pageindex: 1,
  PageSize: 5,
  total: 0,
  totalCount: 0
});

// 获取用户信息
const getUserInfo = () => {
  const store = useCounterStore();
  return store.Users.userNickname || 'admin';
};

// 处理选择变化
const handleSelectionChange = (val: any[]) => {
  selectedRows.value = val;
};

// 取消选择
const cancelSelection = () => {
  tableRef.value?.clearSelection();
};

// 单个删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除【${row.supplierName}】吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    APIs.post("/api/Write/DeleSupplier",row).then(res => {
      if (res.data.code == 100) {
        ElMessage.success("删除成功");
        Data();
      }
    })
  })
};

// 打开新增/编辑弹窗
const openAddDialog = (row: any) => {
  addDialogVisible.is = true;
  if (row == null) {
    // 重置表单数据
    formData.supplierId = "";
    formData.supplierCode = "";
    formData.supplierName = "";
    formData.supplierAbbreviation = "";
    formData.contactInformation = "";
    formData.socialCreditCode = "";
    formData.supplierAddress = "";
    formData.supplierComments = "";
    formData.createName = getUserInfo();
    addDialogVisible.title = "新增供应商";
  } else {
    // 填充编辑数据
    addDialogVisible.title = "编辑供应商";
    Object.assign(formData, row);
  }
};

// 获取数据
const Data = () => {
  APIs.get("/api/Read/GetSupplierList", {
    params: {
      
PageIndex: Page.Pageindex,
PageSize: Page.PageSize,
    }
  }).then(res => {
    tableData.value =res.data.data.data;
    Page.total =  res.data.total ;
    Page.totalCount =  res.data.totalCount ;
  })
};

// 处理新增/编辑确认
const handleAddConfirm = () => {
  // 确保createName始终有值
  formData.createName = formData.createName || getUserInfo();
  
  if (addDialogVisible.title == "新增供应商") {
    APIs.post("/api/Write/AddSupplier", formData).then(res => {
      if (res.data.code == 100) {
        ElMessage.success("添加成功");
        addDialogVisible.is = false;
        Data();
      }
    })
  } else {
    APIs.post("/api/Write/UpdateSupplier", formData).then(res => {
      if (res.data.code == 100) {
        ElMessage.success("修改成功");
        addDialogVisible.is = false;
        Data();
      }
    })
  }
};

// 导出功能
const EXcel = () => {
  // 设置响应类型为blob，这样才能正确处理文件流
  APIs.get("/api/Read/DowGongYing", { responseType: 'blob' }).then(res => {
    // 检查响应是否成功
    if (res.status === 200) {
      // 创建一个blob对象
      const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      
      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      
      // 设置文件名
      const fileName = `供应商数据_${moment().format('YYYYMMDD_HHmmss')}.xlsx`;
      link.download = fileName;
      
      // 触发下载
      document.body.appendChild(link);
      link.click();
      
      // 清理
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      ElMessage.success("导出成功");
    } else {
      ElMessage.error("导出失败");
    }
  }).catch(error => {
    console.error('导出出错:', error);
    ElMessage.error("导出失败，请重试");
  });
};

// 刷新数据
const refreshData = () => {
  Data();
};

// 批量删除
const handleBatchDelete = () => {
  const selectedIds = selectedRows.value.map(row => row.supplierId);
  
  ElMessageBox.confirm(
    `确定要删除选中的${selectedRows.value.length}个供应商吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 根据您的需求，如果批量删除也使用单个删除API，可以循环调用
    // 这里保留当前的批量删除API调用方式，因为它更高效
    APIs.post("/api/Write/PLDeleSupplier", {
      Ids: selectedIds
    }).then(res => {
      if (res.data.code == 100) {
        ElMessage.success("批量删除成功");
        Data();
        cancelSelection();
      }
    })
  });
};

// 搜索功能
const handleSearch = () => {
  Data();
};

// 监听分页变化
watch(Page, () => {
  Data();
});

// 页面加载时获取数据
onMounted(() => {
  Data();
});
</script>

<style scoped>
.supplier-container {
  padding: 20px;
  background-color: #f5f7fa;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 顶部操作栏样式 */
.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  background-color: white;
  padding: 12px 16px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.search-tools {
  display: flex;
  gap: 5px;
}

/* 选中信息样式 */
.selected-info {
  background-color: #ecf5ff;
  padding: 8px 16px;
  border-radius: 4px;
  border: 1px solid #d9ecff;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-text {
  color: #409eff;
  font-size: 14px;
}

/* 表格样式 */
.el-table {
  background-color: white;
  border-radius: 4px;
  overflow: hidden;
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding: 12px 0;
  background-color: white;
  padding: 12px 16px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.total-text {
  color: #606266;
  font-size: 14px;
}

/* 操作按钮样式 */
.operation-btn {
  padding: 0 5px;
  margin: 0 2px;
}

/* 列头搜索样式 */
.column-header-with-search {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 5px;
}

.search-icon {
  cursor: pointer;
  color: #909399;
  transition: color 0.2s;
}

.search-icon:hover {
  color: #409eff;
}

.column-search {
  padding: 5px 0;
}

/* 动画效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .supplier-container {
    padding: 10px;
  }
  
  .action-bar {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }
  
  .action-buttons {
    justify-content: center;
  }
  
  .search-tools {
    justify-content: center;
  }
}
</style>